package com.kylin.system.controller;

import com.kylin.common.core.annotation.NoApiInterceptor;
import com.kylin.common.core.beans.ResultBean;
import com.kylin.common.core.entity.Page;
import com.kylin.common.core.validator.Assert;
import com.kylin.common.core.validator.BeanValidator;
import com.kylin.common.datascope.service.Role;
import com.kylin.common.log.annotation.Log;
import com.kylin.common.log.enums.BusinessType;
import com.kylin.common.poi.excel.EasyExcelUtil;
import com.kylin.system.entity.SysRole;
import com.kylin.system.service.SysMenuService;
import com.kylin.system.service.SysRoleService;
import io.netty.util.internal.UnstableApi;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 角色信息
 * 
 * @author wuhao
 */
@RestController
@RequestMapping("/role")
public class SysRoleController
{
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysMenuService menuService;

//    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/list")
    public ResultBean<Page<SysRole>> list(SysRole role)
    {
        // 构造搜索
        role.getQueryWrapper()
                .like(StringUtils.isNotBlank(role.getRoleName()), "role_name", role.getRoleName())
                .eq(StringUtils.isNotBlank(role.getRoleKey()), "role_key", role.getRoleKey())
                .eq(StringUtils.isNotBlank(role.getStatus()), "status", role.getStatus());

        Page<SysRole> page = new Page<>();
        page = roleService.listPage(page, role);
        return ResultBean.onSuccess(page);
    }

    /**
     * 获取所有的角色列表
     * @return
     * @author wuhao
     * @version 1.0.0 - 2024/10/12
     */
    @GetMapping("/all")
    public ResultBean<List<SysRole>> listAll(SysRole role)
    {
        // 构造搜索
        role.getQueryWrapper()
                .eq( "status", SysRole.STATUS_NORMAL);

        return ResultBean.onSuccess(roleService.list(role));
    }

    /**
     * 根据角色编号获取详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = "/{roleId}")
    public ResultBean<SysRole> getInfo(@PathVariable Long roleId)
    {
        Assert.isBlank("查询编号不能为空", roleId);

        SysRole role = roleService.getById(roleId);
        // 获取对应菜单IDs
        List<Long> menuIdList = menuService.selectMenuListByRoleId(roleId);
        // list 转 数组
        Long[] menuIds = menuIdList.toArray(new Long[menuIdList.size()]);
        role.setMenuIds(menuIds);

        return ResultBean.onSuccess(role);
    }

    /**
     * 新增角色
     */
//    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public ResultBean<Object> add(@RequestBody SysRole role)
    {
        // 参数校验
        BeanValidator.validate(role);
        // roleKey 唯一性校验
        roleService.checkRoleKeyUnique(role);

        roleService.insertRole(role);
        return ResultBean.onSuccess();

    }

    /**
     * 修改保存角色
     */
//    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResultBean<Object> edit(@RequestBody SysRole role)
    {
        // 参数校验
        BeanValidator.validate(role);
        // 验角色是否允许操作
        roleService.checkRoleAllowed(role);
        // roleKey 唯一性校验
        roleService.checkRoleKeyUnique(role);

        roleService.updateRole(role);
        return ResultBean.onSuccess();
    }

    /**
     * 修改保存数据权限
     */
//    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public ResultBean<Object> dataScope(@RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        roleService.authDataScope(role);
        return ResultBean.onSuccess();
    }

    /**
     * 修改保存菜单权限
     */
//    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/menus")
    public ResultBean<Object> updateMenus(@RequestBody SysRole role)
    {
        roleService.authMenus(role);
        return ResultBean.onSuccess();
    }

    /**
     * 删除角色
     */
//    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public ResultBean<Object> remove(@PathVariable Long[] roleIds)
    {
        Assert.isBlank("请选择需要删除的数据", roleIds);
        roleService.deleteRoleByIds(roleIds);
        return ResultBean.onSuccess();
    }

    /**
     * 状态修改
     */
//    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public ResultBean<Object> changeStatus(@RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        roleService.updateStatus(role.getId(), role.getStatus());
        return ResultBean.onSuccess();
    }

    /**
     * 获取角色选择框列表
     */
//    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping("/optionselect")
    public ResultBean<List<SysRole>> optionselect()
    {
        return ResultBean.onSuccess(roleService.list(new SysRole()));
    }

    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
//    @PreAuthorize("@ss.hasPermi('system:role:export')")
    @PostMapping("/export")
    @NoApiInterceptor
    public void export(HttpServletResponse response, SysRole role) throws IOException
    {
        // 构造搜索
        role.getQueryWrapper()
                .like(StringUtils.isNotBlank(role.getRoleName()), "role_name", role.getRoleName())
                .eq(StringUtils.isNotBlank(role.getRoleKey()), "role_key", role.getRoleKey())
                .eq(StringUtils.isNotBlank(role.getStatus()), "status", role.getStatus());
        List<SysRole> list = roleService.list(role);
        EasyExcelUtil.exportExcel(list, "角色数据汇总", "角色数据", SysRole.class, "角色数据导出", response);
    }

}